<?php
/**
 * 短信
 *
 * add by ljp
 */

namespace soa\finance;

use soa\client;

class sms extends client
{

    public $service_url = 'http://finance.interface.kuaidihelp.com/signin.php';
    protected $service_name = 'kuaidihelp_finance';


    /**
     * 按照老接口规范， 重写父类方法
     *
     * @param $api
     * @param array $data
     * @return array
     */
    public function request_params($api, $data){
        return array_merge(array('act'=>$api),$data);
    }

    /**
     * 按照老接口规范， 重写父类方法
     *
     * @param $api
     * @return string
     */
    public function request_api($api){
        return $this->service_url;
    }


    public function request($api, $data = array(), $type = 'GET'){
        $data = $this->request_params($api, $data);
        $api_url = $this->request_api($api);
        switch ($type) {
            case 'POST':
                $response = \artisan\http::post($api_url, $data);
                break;

            case 'GET':
            default:
                $response = \artisan\http::get($api_url, $data);
                break;
        }
        return $this->parse($response);
    }

    public function parse($data){
        $res = json_decode($data,true);
        if(json_last_error() != JSON_ERROR_NONE || !isset($res['data'])){
            return false;
        }

        return $res['data'];
    }

    /**
     * 加锁
     * @return bool
     */
    private function _lock(){
        //TODO lock the require
        return true;
    }


    /**
     * 解锁
     * @return bool
     */
    private function _unlock(){
        //TODO release if has locked
        return true;
    }

    /**
     * 检查短信
     *
     * 按照旧接口形式来做
     *
     * @param $home_shop_id
     * @param $sms_count
     * @param $use_wallet
     * @return bool
     */
    public function check_sms($home_shop_id,$sms_count,$use_wallet = 1){

        if(!$this->_lock()){
            return false;
        }

        $data = array(
            "shop_id" => $home_shop_id,
            'count' => $sms_count,
            'is_wallet' => $use_wallet
        );
        return $this->request('check.sms', $data);
    }

    public function __destruct(){
        $this->_unlock();
    }
}